<template>
  <breadcremb
    :dataSrouce="[
      { key: '/home', title: '首页' },
      { key: '/overload', title: '超偏载信息' },
      { key: '', title: queryParams.status === '1' ? '历史数据' : '当前数据' }
    ]"
  />
  <div>
    <div class="search-container">
      <el-form ref="formRef" :model="form" inline label-width="68px" class="custom-el-form">
        <el-form-item label="作业编号" prop="batchId">
          <el-input
            v-model="form.batchId"
            placeholder="请输入作业编号"
            style="width: 160px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset(formRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-descriptions title="" border style="margin-bottom: 20px">
      <el-descriptions-item label="司机姓名">{{ driverInfo.userName }}</el-descriptions-item>
      <el-descriptions-item label="身份证号码">{{ driverInfo.idNum }}</el-descriptions-item>
      <el-descriptions-item label="性别">{{ driverInfo.gender }}</el-descriptions-item>
      <el-descriptions-item label="车牌号">
        <el-tag size="small">{{ driverInfo.carNum }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="联系电话">{{ driverInfo.phone }}</el-descriptions-item>
    </el-descriptions>
    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column prop="batchId" label="作业编号" />
      <el-table-column prop="templateNum" label="车板号" />
      <el-table-column prop="containerNum" label="集装箱编号" />
      <el-table-column prop="realTotalWeight" label="总重量/kg" />
      <el-table-column prop="" label="是否超载">
        <template #default="scope">
          <span
            :style="{
              color: scope.row.realTotalWeight > scope.row.totalWeight ? 'red' : '#606266'
            }"
            >{{ scope.row.realTotalWeight > scope.row.totalWeight ? '是' : '否' }}</span
          >
        </template>
      </el-table-column>
      <el-table-column prop="realFrontRear" label="前后偏载/kg" />
      <el-table-column prop="" label="是否偏载">
        <template #default="scope">
          <span
            :style="{ color: scope.row.realFrontRear > scope.row.frontRear ? 'red' : '#606266' }"
            >{{ scope.row.realFrontRear > scope.row.frontRear ? '是' : '否' }}</span
          >
        </template>
      </el-table-column>
      <el-table-column prop="realLeftRight" label="左右偏载/mm" />
      <el-table-column prop="" label="是否偏载">
        <template #default="scope">
          <span
            :style="{ color: scope.row.realLeftRight > scope.row.leftRight ? 'red' : '#606266' }"
            >{{ scope.row.realLeftRight > scope.row.leftRight ? '是' : '否' }}</span
          >
        </template>
      </el-table-column>
      <el-table-column prop="idNum" label="检测时间" width="160">
        <template #default="scope">{{
          moment(scope.row.updateTime).format('YYYY-MM-DD HH:MM:ss')
        }}</template>
      </el-table-column>
      <el-table-column label="操作" width="110" v-if="userStore.userinfo?.userId === '0'">
        <template #default="scope">
          <el-popconfirm title="是否确认删除？" @confirm="handleDel(scope.row)">
            <template #reference>
              <el-button link type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="dataTotal"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import moment from 'moment'
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElDescriptions,
  ElDescriptionsItem,
  ElTag,
  ElTable,
  ElTableColumn,
  ElPopconfirm,
  ElButton,
  ElPagination,
  ElMessage
} from 'element-plus'
import type { FormInstance } from 'element-plus'
import Breadcremb from '@/components/breadcrumb/index.vue'
import http from '@/utils/request'
import { useUserStore } from '@/stores/user'

interface FormValue {
  batchId: string
}

const router = useRouter()
const userStore = useUserStore()
const queryParams = router.currentRoute.value.query
const formRef = ref<FormInstance>()
const form = reactive<FormValue>({
  batchId: ''
})
const driverInfo = ref({
  userName: '',
  idNum: '',
  gender: '',
  carNum: '',
  phone: ''
})

const tableData = ref([])
const dataTotal = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

const handleSearch = () => {
  initData()
}

const handleReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  initData()
}

onBeforeMount(() => {
  initData()
})

const initData = async () => {
  const { id, status } = queryParams
  const params = {
    batchId: form.batchId,
    status: status === '1' ? 1 : 0, // false - 0 进行中 1 空闲 true
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    userId: id
  }
  const res = await http.get('/shippingRecord/queryUserRecords', params)
  if (res.code === '200') {
    const { userName, idNum, gender, carNum, phone, recordInfoResponses, total } = res.result || {}
    driverInfo.value = {
      userName,
      idNum,
      gender: Number(gender) === 1 ? '男' : '女',
      carNum,
      phone
    }
    tableData.value = recordInfoResponses || []
    dataTotal.value = total || 0
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  initData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  initData()
}

const handleDel = async (data: any) => {
  const res = await http.post('/shippingRecord/remove', { id: data.id })
  const { code, desc } = res || {}
  if (code === '200') {
    ElMessage({
      message: '删除成功',
      type: 'success'
    })
    initData()
  } else {
    ElMessage({
      message: desc || '删除失败',
      type: 'error'
    })
  }
}
</script>

<style scoped lang="scss">
.search-container {
  display: flex;
  justify-content: space-between;
}

.table-pagination {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>
